<template>
    <!-- 授权用户 -->
    <el-dialog :close-on-click-modal="false" :visible.sync="visible" append-to-body title="选择用户" top="5vh"
               width="50%">
        <el-form ref="queryForm" :inline="true" :model="queryParams" size="small">
            <el-form-item label="用户名称" prop="userName">
                <el-input
                    v-model="queryParams.userName"
                    clearable
                    placeholder="请输入用户名称"
                    @keyup.enter.native="handleQuery"
                />
            </el-form-item>
            <el-form-item label="手机号码" prop="phonenumber">
                <el-input
                    v-model="queryParams.phonenumber"
                    clearable
                    placeholder="请输入手机号码"
                    @keyup.enter.native="handleQuery"
                />
            </el-form-item>
            <el-form-item>
                <el-button icon="el-icon-search" size="mini" type="primary" @click="handleQuery">搜索</el-button>
                <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
            </el-form-item>
        </el-form>
        <el-row>
            <el-col :span="5">
                <!--科室树-->
                <dept-tree
                    ref="deptTree"
                    :excess-height="400"
                    :org-id="queryParams.orgId"
                    @treeClick="treeClick"
                />
            </el-col>
            <el-col :span="19" :xs="24">
                <el-row>
                    <el-table ref="table" :data="userList" :stripe='true' border height="300px"
                              @select="onTableSelect" @selection-change="handleSelectionChange" @select-all="selectAll">
                        <el-table-column type="selection" width="55"></el-table-column>
                        <el-table-column :show-overflow-tooltip="true" label="所属机构" prop="orgName"/>
                        <el-table-column :show-overflow-tooltip="true" label="所属科室" prop="dept.deptName"/>
                        <el-table-column :show-overflow-tooltip="true" label="用户名称" prop="userName"/>
                        <el-table-column :show-overflow-tooltip="true" label="用户昵称" prop="nickName"/>
                        <el-table-column :show-overflow-tooltip="true" label="邮箱" prop="email"/>
                        <el-table-column :show-overflow-tooltip="true" label="手机" prop="phonenumber"/>
                        <el-table-column align="center" label="状态" prop="status">
                            <template slot-scope="scope">
                                <dict-tag :options="dict.type.sys_normal_disable" :value="scope.row.status"/>
                            </template>
                        </el-table-column>
                        <el-table-column align="center" label="创建时间" prop="createTime" width="180">
                            <template slot-scope="scope">
                                <span>{{ parseTime(scope.row.createTime) }}</span>
                            </template>
                        </el-table-column>
                    </el-table>
                    <pagination
                        v-show="total>0"
                        :limit.sync="queryParams.pageSize"
                        :page.sync="queryParams.pageNum"
                        :total="total"
                        @pagination="getList"
                    />
                </el-row>
                <el-row style="margin-top: 40px">
                    <el-col :span="12">
                        <el-card class="box-card">
                            <div style="height: 240px;">
                                <span>已授权人员：{{ haveBeenAuthorized.length }}人</span>
                                <div class="div-tag">
                                    <el-tag v-for="tag in haveBeenAuthorized"
                                            :key="tag.name"
                                            :type="tag.type"
                                            class="tag-margin">
                                        {{ tag.name }}
                                    </el-tag>
                                </div>
                            </div>
                        </el-card>
                    </el-col>
                    <el-col :span="12">
                        <el-card class="box-card">
                            <div style="height: 240px;">
                                <span>已选人员：</span>
                                <el-button :disabled="tags.length === 0" size="mini" type="danger" @click="emptyTags">
                                    清空
                                </el-button>
                                <div class="div-tag">
                                    <el-tag v-for="tag in tags"
                                            :key="tag.name"
                                            :type="tag.type"
                                            class="tag-margin"
                                            closable
                                            @close="handleClose(tag)">
                                        {{ tag.name }}
                                    </el-tag>
                                </div>
                            </div>
                        </el-card>
                    </el-col>

                </el-row>
            </el-col>
        </el-row>
        <div slot="footer" class="dialog-footer">
            <el-button size="small" type="primary" @click="handleSelectUser">保 存</el-button>
            <el-button size="small" @click="visible = false">取 消</el-button>
        </div>
    </el-dialog>
</template>

<script>
import {
    unallocatedUserList,
    authUserSelectAll,
    allocated,
    deptGroupUnallocatedUserList,
    deptGroupAuthUserSelectAll,
    deptGroupAllocated
} from "@/api/system/role";

export default {
    dicts: ['sys_normal_disable'],
    data () {
        return {
            userInfo: this.$store.state.user.userInfo,
            // 遮罩层
            visible: false,
            // 选中数组值
            userIds: [],
            // 总条数
            total: 0,
            // 未授权用户数据
            userList: [],
            // 查询参数
            queryParams: {
                pageNum: 1,
                pageSize: 10,
                roleId: undefined,
                userName: undefined,
                phonenumber: undefined,
                deptGroupId: undefined,
                businessType: ''
            },
            // 已添加人员
            tags: [],
            // 已授权人员
            haveBeenAuthorized: [],
            // 已勾选列表数据
            selection: []
        };
    },
    methods: {
        /** 删除已选择人员 */
        handleClose (tag) {
            this.$nextTick(() => {
                this.$refs.table.toggleRowSelection(this.selection.filter((item) => {
                    return item.userId === tag.userId;
                }), false)
            })
            this.tags.splice(this.tags.indexOf(tag), 1)
            this.getList()
        },
        onTableSelect (rows, row) {
            let selected = rows.length && rows.indexOf(row) !== -1
            if (!selected) {
                let exclusionOfExistence = this.tags.filter((item) => {
                    return item.userId !== row.userId;
                });
                this.tags = exclusionOfExistence
            }
        },
        // 多选框选中数据
        handleSelectionChange (selection) {
            this.selection = selection
            this.resArr(selection, this.tags)
        },
        selectAll (selection) {
            if (selection.length === 0) {
                return this.tags = []
            }
            this.resArr(selection, this.tags)
        },
        /** 清空待选 */
        emptyTags () {
            this.tags = []
            this.$refs.table.clearSelection()
        },
        resArr (arr1, arr2) {
            let resArr = arr1.filter((v) => arr2.every((val) => val.userId !== v.userId))
            return resArr.forEach(item => {
                let tag = {
                    name: item.dept.deptName + ' | ' + item.nickName,
                    userId: item.userId,
                    type: 'warning',
                    isNew: true
                }
                this.tags.push(tag)
            })
        },
        // 显示弹框
        show (queryParams) {
            this.haveBeenAuthorized = []
            this.queryParams.businessType = queryParams.businessType;
            this.queryParams.roleId = queryParams.roleId;
            this.queryParams.deptGroupId = queryParams.deptGroupId;
            this.queryParams.orgId = this.userInfo.orgId || queryParams.orgId
            this.getList();
            if (this.queryParams.businessType === '1') {
                allocated(this.queryParams).then(res => {
                    let data = res.data
                    data.forEach(item => {
                        let tag = {
                            name: item.dept.deptName + '|' + item.nickName,
                            userId: item.userId,
                            type: 'success',
                            isNew: false
                        }
                        this.haveBeenAuthorized.push(tag)
                    })
                })
            } else if (this.queryParams.businessType === '2') {
                deptGroupAllocated(this.queryParams).then(res => {
                    let data = res.data
                    data.forEach(item => {
                        let tag = {
                            name: item.dept.deptName + ' | ' + item.nickName,
                            userId: item.userId,
                            type: 'success',
                            isNew: false
                        }
                        this.haveBeenAuthorized.push(tag)
                    })
                })
            }

            this.visible = true;
        },
        // 查询表数据
        getList () {
            if (this.queryParams.businessType === '1') {
                unallocatedUserList(this.queryParams).then(res => {
                    this.userList = res.rows;
                    this.total = res.total;
                    // 列表默认选中
                    this.$nextTick(() => {
                        this.userList.forEach(row => {
                            this.tags.forEach(selected => {
                                if (selected.userId === row.userId) {
                                    this.$refs.table.toggleRowSelection(row, true);
                                }
                            })
                        })
                    })
                });
            } else if (this.queryParams.businessType === '2') {
                deptGroupUnallocatedUserList(this.queryParams).then(res => {
                    this.userList = res.rows;
                    this.total = res.total;
                    // 列表默认选中
                    this.$nextTick(() => {
                        this.userList.forEach(row => {
                            this.tags.forEach(selected => {
                                if (selected.userId === row.userId) {
                                    this.$refs.table.toggleRowSelection(row, true);
                                }
                            })
                        })
                    })
                });
            }

        },
        /** 搜索按钮操作 */
        handleQuery () {
            this.queryParams.deptId = ''
            this.queryParams.pageNum = 1;
            this.getList();
        },
        /** 重置按钮操作 */
        resetQuery () {
            this.resetForm("queryForm");
            this.handleQuery();
        },
        /** 选择授权用户操作 */
        handleSelectUser () {
            this.userIds = this.tags.map(item => item.userId);
            const userIds = this.userIds.join(",");
            if (userIds === "") {
                this.$modal.msgError("请选择要分配的用户");
                return;
            }
            if (this.queryParams.businessType === '1') {
                const roleId = this.queryParams.roleId;
                let param = {roleId: roleId, list: this.tags}
                authUserSelectAll(param).then(res => {
                    this.$modal.msgSuccess(res.msg);
                    if (res.code === 200) {
                        this.visible = false;
                        this.emptyTags()
                        this.$emit("ok");
                    }
                });
            } else if (this.queryParams.businessType === '2') {
                const deptGroupId = this.queryParams.deptGroupId;
                let param = {deptGroupId: deptGroupId, list: this.tags}
                deptGroupAuthUserSelectAll(param).then(res => {
                    this.$modal.msgSuccess(res.msg);
                    if (res.code === 200) {
                        this.visible = false;
                        this.emptyTags()
                        this.$emit("ok");
                    }
                });
            }

        },
        /** 左侧科室树节点点击事件 */
        treeClick (obj) {
            this.queryParams.deptId = obj.id
            this.getList()
        },
    }
};
</script>

<style lang="scss" scoped>
::v-deep .el-dialog__footer {
    padding-top: 30px;
}

.box-card {
    margin: 10px 10px 10px 10px;
    height: 280px;
}

.tag-margin {
    margin: 10px 10px 0px 10px
}

.div-tag {
    margin: 10px 5px 5px 10px;
    height: 100%;
    overflow-y: auto
}

</style>
